﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Garden.Model;
using Kaixin.BLL;
using Kaixin.BLL.Helper;
using RegexHelper = Garden.Helper.RegexHelper;
namespace Garden.Func
{
    public class Granary
    {
        private string _verify;//验证字符串
        private LogWrite _log;

        public Granary(LogWrite log)
        {
            _log = log;
            string myGarden = WebHelper.Get("http://www.kaixin001.com/!house/garden/index.php");
            List<GroupCollection> list = RegexHelper.Matches(myGarden, RegexHelper.VerifyReg);
            if (list.Count == 0)
            {
                return;
            }
            _verify = list[0][1].Value;
        }

        /// <summary>
        /// 更新种子列表并返回最新列表
        /// </summary>
        /// <returns></returns>
        public List<Seed> UpdateGranaryList()
        {
            string url = "http://www.kaixin001.com/!house/!garden//mygranary.php?r=0.7427828791551292&verify=" + _verify;
            string data = WebHelper.Get(url);
            List<GroupCollection> list = RegexHelper.Matches(data, RegexHelper.FruitReg);
            if (list.Count != 0)
            {
                Utility.CreateOrUpdateXMLFile(Utility.GRANARYFILENAME, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + list[0][0].Value);
            }
            else
            {
                if (!Utility.IsExistGranaryXMLFile())
                    throw new Exception("列表读取错误");
            }

            return GetGranaryList();
        }
        /// <summary>
        /// 返回种子列表
        /// </summary>
        /// <returns></returns>
        public List<Seed> GetGranaryList()
        {
            List<Seed> list = new List<Seed>();
            if (!Utility.IsExistGranaryXMLFile())
            {
                _log("谷物库配置文件不存在，系统将自动为其创建一份");
                return UpdateGranaryList();
            }
            XDocument doc = XDocument.Load(Utility.GRANARYFILENAME);
            var items = from i in doc.Root.Elements() select i;
            foreach (var item in items)
            {
                Seed s = new Seed
                             {
                                 ID = item.Element("seedid").Value,
                                 name = item.Element("name").Value
                             };
                list.Add(s);
            }

            return list;
        }
    }
}
